package com.sanno.user.controller;

import com.auth0.jwt.JWT;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sanno.common.entity.SccDrugstore;
import com.sanno.common.entity.SncUserLogin;
import com.sanno.common.result.Result;
import com.sanno.common.result.ResultCodeEnum;
import com.sanno.user.service.UserService;
import com.sanno.user.util.HttpUtils;
import com.sanno.user.util.JWTutil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.http.HttpResponse;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.net.InetAddress;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

@Controller
@Api(tags = "用户管理")
@RequestMapping("/user")
@CrossOrigin
public class UserController {

    @Resource
    private UserService userServiceImpl;

    @RequestMapping(value = "login",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "用户登录",notes = "根据用户名和密码登录",httpMethod = "GET")
    public Result login(String phone,String password)throws Exception{

        //获得电脑IP地址
        String IP = InetAddress.getLocalHost().getHostAddress();
        SncUserLogin sncUserLogin = new SncUserLogin();

        QueryWrapper<SncUserLogin> queryWrapper = new QueryWrapper<SncUserLogin>();
         queryWrapper.eq("phone", phone);
         queryWrapper.eq("password", password);


//         // 验证码
//        String host = "https://cxkjsms.market.alicloudapi.com";
//        String path = "/chuangxinsms/dxjk";
//        String method = "POST";
//        String appcode = "4e2cf3c4c1e44ec5be75588a25df50f6";//开通服务后 买家中心-查看AppCode
//        Map<String, String> headers = new HashMap<String, String>();
//        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
//        headers.put("Authorization", "APPCODE " + appcode);
//        Map<String, String> querys = new HashMap<String, String>();
//        querys.put("content", "【三诺】你的验证码是：3035，3分钟内有效！");
//        querys.put("mobile", phone);
//        Map<String, String> bodys = new HashMap<String, String>();
//
//        try {
//
//            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
//            System.out.println(response.toString());
//            //获取response的body
////            System.out.println(EntityUtils.toString(response.getEntity()));
//        } catch (Exception e) {
//            e.printStackTrace();
//        }


//        queryWrapper.eq("ip",IP);

        SncUserLogin one = userServiceImpl.getOne(queryWrapper,true);
        userServiceImpl.insertIp(one.getId(),IP);


        if (one==null){
            return Result.fail();
        }

        try {

            //定义Map集合，用来存放payload（用户信息）
            Map<String, String> map = new HashMap<>();
            map.put("id", one.getId().toString());
            map.put("name", one.getName());
            map.put("phone",one.getPhone());

            //调用工具类中的方法，获得token
            String token = JWTutil.getToken(map);
            return Result.ok(token);

        } catch(Exception e){
            e.printStackTrace();
            return Result.fail(e);
        }

   }

    @RequestMapping(value = "login1",method = RequestMethod.GET)
    @ResponseBody
    public Result login1(String pass){
        System.out.println(pass);
        DecodedJWT decodedJWT = JWTutil.getDecodedJWT(pass);
        System.out.println(decodedJWT);
        DecodedJWT decode = JWT.decode(pass);
        byte[] decoded = Base64.getDecoder().decode(decode.getPayload());

        String decodeStr = new String(decoded);
        System.out.println(decodeStr);
        return Result.ok(decodeStr);
    }

    @RequestMapping(value = "updateName",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "修改用户信息",notes = "根据账户名修改用户信息",httpMethod = "POST")
    public Result updateUserName(SncUserLogin sncUserLogin) throws Exception{
        boolean b = userServiceImpl.updateName(sncUserLogin);

        return Result.ok(ResultCodeEnum.SUCCESS);
    }

    @RequestMapping(value = "updatePwd",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "修改用户信息",notes = "根据账户名修改用户信息",httpMethod = "POST")
    public Result updateUserPwd(SncUserLogin sncUserLogin) throws Exception{
        boolean b = userServiceImpl.updatePwd(sncUserLogin);

        return Result.ok(ResultCodeEnum.SUCCESS);
    }
}
